package cn.itcast.dubbo.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import java.util.Random;

/**
 * @author Hujf
 * @title: MyAbstractRoutingDataSource
 * @description: TODO
 * @date 2020/7/23 0023下午 2:41
 */

public class MyAbstractRoutingDataSource extends AbstractRoutingDataSource {
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    private int num=3;

    @Override
    protected Object determineCurrentLookupKey() {
        String typeKey = DbContextHolder.getDbType();
        if(typeKey==DbContextHolder.WRITE){
            log.info("使用了写库");
            System.out.println("使用了写库{}");
            return typeKey;
        }

        int sum = new Random().nextInt(num)+1;
        log.info("使用了读库{}", sum);
        System.out.println("使用了读库{}");
        return DbContextHolder.READ + sum;
    }

}
